<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Models\Cart;
use App\Models\Item;
use App\Models\Order;
use App\Models\OrderAction;
use App\Models\OrderItem;
use App\Models\OrderShipping;
use App\Models\SellerJPush;
use App\Models\Shop;
use App\Models\Trade;

class CartController extends ApiController
{

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getItemList(){
        $query = Cart::with(['items'=>function($query){
            return $query->where('uid', $this->uid);
        }])->where('uid', $this->uid);

        $items = $this->request->input('items');
        if (is_array($items)) $query = $query->whereIn('itemid', $items);

        $shops = $query->groupBy('shop_id')->get(['id', 'uid', 'shop_id', 'shop_name'])->map(function ($shop){
            $shop->items = $shop->items->map(function ($item){
                $item->thumb = image_url($item->thumb);
                $item->image = image_url($item->image);
                return $item;
            });
            return $shop;
        });

        return ajaxReturn(['items'=>$shops, 'count'=>$shops->count()]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function add()
    {
        $itemid = $this->request->input('itemid');
        $quantity = $this->request->input('quantity');
        if ($itemid && $quantity) {
            if (Cart::where(['uid'=>$this->uid, 'itemid'=>$itemid])->exists())
            {
                Cart::where(['uid'=>$this->uid, 'itemid'=>$itemid])->increment('quantity', $quantity);
            } else {
                addToCart($this->uid, $itemid, $quantity);
            }
        }
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateQuantity()
    {
        $itemid = $this->request->input('itemid');
        $quantity = $this->request->input('quantity');
        if ($itemid && $quantity) {
            Cart::where(['uid'=>$this->uid, 'itemid'=>$itemid])->update(['quantity'=>$quantity]);
        }
        return ajaxReturn();
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function settlement()
    {
        $shops = $this->request->input('shops');
        $shipping_type = $this->request->input('shipping_type');
        $pay_type = $this->request->input('pay_type');
        $address  = $this->request->input('address');

        $orders = [];
        foreach ($shops as $data) {

            $shop = Shop::find($data['shop_id']);
            $order_no = createOrderNo();
            $trade_no = createTradeNo();
            $total_fee = 0;

            $order = Order::create([
                'buyer_uid'=>$this->uid,
                'buyer_name'=>$this->username,
                'buyer_message'=>$data['buyer_message'],
                'seller_uid'=>$shop->uid,
                'seller_name'=>$shop->username,
                'shop_id'=>$shop->shop_id,
                'shop_name'=>$shop->shop_name,
                'order_no'=>$order_no,
                'order_fee'=>$total_fee,
                'shipping_fee'=>0,
                'total_fee'=>$total_fee,
                'pay_type'=>$pay_type,
                'pay_status'=>0,
                'shipping_type'=>$shipping_type,
                'shipping_status'=>0,
                'receive_status'=>0,
                'created_at'=>time(),
                'trade_no'=>$trade_no,
                'trade_status'=>1,
            ]);

            $subject = $body = '';
            foreach ($data['items'] as $item) {
                $order->items()->insert([
                    'uid'=>$this->uid,
                    'order_id'=>$order->order_id,
                    'itemid'=>$item['itemid'],
                    'title'=>$item['title'],
                    'price'=>$item['price'],
                    'thumb'=>$item['thumb'],
                    'image'=>$item['image'],
                    'quantity'=>$item['quantity'],
                    'total_fee'=>$item['price'] * $item['quantity']
                ]);
                $total_fee+= $item['price'] * $item['quantity'];
                if (!$subject) $subject = $item['title'];
                if (!$body) $body = $item['title'];
                //更新销量
                $shop->increment('total_sold', $item['quantity']);
                Item::where('itemid', $item['itemid'])->increment('sold', $item['quantity']);
                //从购物车删除
                Cart::where('uid', $this->uid)->where('itemid', $item['itemid'])->delete();
            }

            $order->update([
                'order_fee'=>$total_fee,
                'total_fee'=>$total_fee,
            ]);

            $order->shipping()->insert([
                'uid'=>$this->uid,
                'order_id'=>$order->order_id,
                'shipping_type'=>$shipping_type,
                'consignee'=>$address['consignee'],
                'phone'=>$address['phone'],
                'province'=>$address['province'],
                'city'=>$address['city'],
                'district'=>$address['district'],
                'street'=>$address['street'],
                'created_at'=>time()
            ]);

            //添加操作记录
            $order->actions()->insert([
                'order_id'=>$order->order_id,
                'uid'=>$this->uid,
                'username'=>$this->username,
                'content'=>trans('mall.auction success'),
                'created_at'=>time()
            ]);

            if ($pay_type == 1) {
                $order->trade()->insert([
                    'payer_uid'=>$this->uid,
                    'payer_name'=>$this->username,
                    'payee_uid'=>$shop->uid,
                    'payee_name'=>$shop->username,
                    'pay_type'=>'alipay',
                    'pay_status'=>0,
                    'trade_no'=>$trade_no,
                    'subject'=>$subject,
                    'body'=>$body,
                    'total_amount'=>$total_fee,
                    'trade_type'=>'SHOPPING',
                    'trade_status'=>1,
                    'created_at'=>time(),
                    'out_trade_no'=>$order_no,
                ]);
            } else {
                $order->update([
                    'pay_status'=>1,
                    'pay_at'=>time(),
                    'trade_status'=>2
                ]);
            }

            //发送APP通知
            $registration = SellerJPush::where('uid', $shop->uid)->first();
            if ($registration->ios) {
                selerAppPush()->push()->setPlatform('ios')
                    ->addRegistrationId($registration->ios)
                    ->iosNotification('你有新的订单')
                    ->send();
            }

            if ($registration->android) {
                selerAppPush()->push()->setPlatform('android')
                    ->addRegistrationId($registration->android)
                    ->androidNotification('你有新的订单')
                    ->send();
            }

            $orders[] = $order;
        }
        return ajaxReturn(['orders'=>$orders]);
    }
}
